<template>
  <div class="set-wrapper">
    <el-form :inline="true">
      <el-form-item label="编码信息：">
        <el-input style="width: 150px;" v-model="searchParam.code"></el-input>
      </el-form-item>
      <el-form-item label="产品名称：">
        <el-input style="width: 150px;" v-model="searchParam.name"></el-input>
      </el-form-item>
      <el-form-item label="产品描述：">
        <el-input style="width: 150px;" v-model="searchParam.description"></el-input>
      </el-form-item>
      <el-form-item label="一级分类：">
        <el-select style="width: 150px;" clearable v-model="searchParam.typeIdList" placeholder="请选择">
          <el-option
            v-for="item in firstTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchItem(true)">查询</el-button>
        <el-button @click="resetSearch()">重置</el-button>
        <el-button type="primary" @click="openItemDialog(false,false)">新增</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table :height="tableHeight" :data="tableData" border style="width: 100%">
        <el-table-column label="序号" type="index" width="100" align="center"></el-table-column>
        <el-table-column label="V1编码" prop="codeV1" min-width="100" align="center"></el-table-column>
        <el-table-column label="V2编码" prop="codeV2" min-width="100" align="center"></el-table-column>
        <el-table-column label="V3编码" prop="codeV3" min-width="100" align="center"></el-table-column>
        <el-table-column label="系统编码" prop="codeV4" min-width="100" align="center"></el-table-column>
        <el-table-column label="产品名称" prop="name" min-width="100" align="center"></el-table-column>
        <el-table-column label="操作" align="center"  width="180">
            <template slot-scope="scope">
              <el-button @click="openItemDialog(scope.row, true)" type="text" size="small">查看</el-button>
              <el-button v-if="isManager" @click="openItemDialog(scope.row, false)" type="text" size="small">编辑</el-button>
              <el-button v-if="isManager" @click="delItem(scope.row)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
      </el-table>
    </div>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <el-dialog :fullscreen="true" :visible.sync="itemDialog">
      <div slot="title">
        <h2 style="text-align:center;margin-bottom:0;">产品详情</h2>
      </div>
      <div class="form-wrapper">
        <el-form ref="form" :model="form" label-width="200px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="系统编码">
                <el-input v-model="form.codeV4" style="width: calc(100% - 75px);" disabled placeholder="由系统自动生成"></el-input>
                <el-button :disabled="!form.id || isCheck" @click="openUpdate">修改</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="V1编码">
                <el-input :disabled="isCheck" v-model="form.codeV1"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="V2编码">
                <el-input :disabled="isCheck" v-model="form.codeV2"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="V3编码">
                <el-input :disabled="isCheck" v-model="form.codeV3"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="产品名称">
                <el-input :disabled="isCheck" v-model="form.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="所属公司">
                <el-select :disabled="isCheck" v-model="form.companyId" style="width: 100%;" placeholder="请选择所属公司">
                  <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item style="font-weight: bold;" label="产品描述">
            <el-input :disabled="isCheck" type="textarea" :autosize="{ minRows: 4}" v-model="form.description"></el-input>
          </el-form-item>
          <el-form-item style="font-weight: bold;" label="一级分类">
            <el-table :data="form.firstTypeList" border style="width: 100%; margin-top:10px;font-weight: normal;">
              <el-table-column label="一级分类类型" prop="kpiItemKey" min-width="180" align="center">
                <template slot-scope="scope">
                  <el-select :disabled="isCheck" v-model="scope.row.typeId" style="width: 100%;">
                    <el-option v-for="item in firstTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column v-if="!isCheck" label="操作" align="center" min-width="50">
                <template slot-scope="scope">
                  <i v-if="(form.firstTypeList.length -1) === scope.$index && !isCheck" @click="addItem(scope.$index,form.firstTypeList, 1)" class="el-icon-circle-plus" style="cursor:pointer;"></i>
                  <i v-if="!isCheck" @click="removeItem(scope.$index, form.firstTypeList)" class="el-icon-remove" style="cursor:pointer;"></i>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item style="font-weight: bold;" label="二级分类">
            <el-table :data="form.functionList" border style="width: 100%; margin-top:10px;font-weight: normal;">
              <el-table-column label="二级分类类型" prop="kpiItemKey" min-width="180" align="center">
                <template slot-scope="scope">
                  <el-select :disabled="isCheck" v-model="scope.row.secondTypeId" style="width: 100%;" @change="getDetailFunctionList(scope.row)">
                    <el-option v-for="item in functionList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="功能" prop="kpiItemKey" min-width="180" align="center">
                <template slot-scope="scope">
                  <div v-for="(child, idx) in scope.row.detailFunctionList" :key="child.id" style="text-align:left;margin-bottom:5px;">
                    <el-select :disabled="isCheck" v-model="child.functionId" style="width: calc(100% - 60px);">
                      <el-option v-for="item in scope.row.options" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                    <i v-if="(scope.row.detailFunctionList.length -1) === idx && !isCheck" @click="addItem(idx, scope.row.detailFunctionList, 3)" class="el-icon-circle-plus" style="cursor:pointer;"></i>
                    <i v-if="!isCheck" @click="removeItem(idx, scope.row.detailFunctionList)" class="el-icon-remove" style="cursor:pointer;"></i>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="开关" prop="kpiItemKey" min-width="130" align="center">
                <template slot-scope="scope">
                  <div style="margin-bottom:5px;" v-for="child in scope.row.detailFunctionList" :key="child.id">
                    <el-select :disabled="isCheck" v-model="child.switchNoId" style="width: 100%;">
                      <el-option v-for="item in switchNoList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" v-if="!isCheck" align="center" min-width="50">
                <template slot-scope="scope">
                  <i v-if="(form.functionList.length -1) === scope.$index && !isCheck" @click="addItem(scope.$index, form.functionList, 2)" class="el-icon-circle-plus" style="cursor:pointer;"></i>
                  <i v-if="!isCheck" @click="removeItem(scope.$index, form.functionList)" class="el-icon-remove" style="cursor:pointer;"></i>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-row :gutter="20" v-for="num in characterCounter" :key="num">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" :label="characterList[(num-1) * 2].name">
                <el-select :key="'select' + characterList[(num-1) * 2].id + '1'" multiple v-if="(characterList[(num-1) * 2].name === '颜色' || characterList[(num-1) * 2].name === '材质') && !form.id" :disabled="isCheck" clearable v-model="characterList[(num-1) * 2].val" style="width: 100%;">
                  <el-option v-for="item in characterList[(num-1) * 2].options" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
                <el-select :key="'select' + characterList[(num-1) * 2].id + '3'" v-else :disabled="isCheck" clearable v-model="characterList[(num-1) * 2].val" style="width: 100%;">
                  <el-option v-for="item in characterList[(num-1) * 2].options" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="characterList[(num-1) * 2 + 1]">
              <el-form-item style="font-weight: bold;" :label="characterList[(num-1) * 2 + 1].name">
                <el-select :key="'select' + characterList[(num-1) * 2 + 1].id + '2'" multiple v-if="(characterList[(num-1) * 2 + 1].name === '颜色' || characterList[(num-1) * 2 + 1].name === '材质') && !form.id" :disabled="isCheck" clearable v-model="characterList[(num-1) * 2 + 1].val" style="width: 100%;">
                  <el-option v-for="item in characterList[(num-1) * 2 + 1].options" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
                <el-select :key="'select' + characterList[(num-1) * 2 + 1].id + '4'" v-else :disabled="isCheck" clearable v-model="characterList[(num-1) * 2 + 1].val" style="width: 100%;">
                  <el-option v-for="item in characterList[(num-1) * 2 + 1].options" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button v-if="!isCheck && isManager" type="primary" @click="saveForm">保存</el-button>
            <el-button v-if="!form.id" type="primary" @click="preview">预览</el-button>
            <el-button @click="itemDialog = false;">关闭</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog title="修改系统编码" :visible.sync="showUpdate" width="600px"> 
      <el-form :model="form" style="padding-right:100px;">
        <el-form-item label="系统编码：" label-width="120px">
          <el-input type="text" v-model="codeV4" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showUpdate = false">取 消</el-button>
        <el-button type="primary" @click="saveUpdate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import dingMixin from  '@/mixins/ding'
  import formUtil from '@/utils/formUtil'

  export default {
    data () {
      return {
        showUpdate: false,
        pageSize: 10,
        page:1,
        totalPage: 0,
        itemDialog: false,
        codeV4: '',
        searchParam: {
          code: '',
          description: '',
          typeIdList: [],
          name: '',
        },
        form: {
          codeV1: '',
          codeV2: '',
          codeV3: '',
          codeV4: '',
          name: '',
          companyId: '',
          description: '',
          firstTypeList: [{typeId: ''}],
          functionList: [],
          characterList: []
        },
        formVerify: {
          name: '请输入产品名称',
          companyId: '请选择所属公司'
        },
        tableData: [],
        code: '',
        tableHeight: window.tableHeight,
        inputObjArr: [],
        companyList: [],
        characterList: [],
        characterCounter: 0,
        firstTypeList: [],
        functionList: [],
        switchNoList:[],
        isCheck: false
      }
    },
    mixins: [dingMixin],
    activated() {
      this.tableHeight = document.documentElement['clientHeight'] - 290
      window.onresize = () => {
        this.tableHeight = document.documentElement['clientHeight'] - 290
      }
    },
    computed: {
      isManager() {
        return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1326005028520824835')
      }
    },
    async mounted(){
      this.searchItem(true);
      let dictList = await this.$httpN.get('pac/type/title');
      this.switchNoList = await this.$httpN.get('pac/type/switchNoList');
      this.switchNoList.unshift({
        name: '无',
        id: ''
      })
      this.companyList = dictList[0].children;
      this.firstTypeList = dictList[1].children;
      this.functionList = dictList[2].children;
      let characterList = formUtil.deepCopy(dictList[3].children);
      characterList.forEach(async (item) => {
          item.val = '';
        item.options = await this.$httpN.postQ('pac/type/listByPid', {pid: item.id});
      })

      this.characterList = characterList;
      this.characterCounter = (characterList.length % 2 === 1)? ((characterList.length + 1) / 2): characterList.length / 2;
    },
    methods: {
      //获取小项列表
      async searchItem(init) {
        if(init) this.page = 1;
        let data = await this.$httpN.postB('pac/product/list', {
          code: this.searchParam.code,
          description: this.searchParam.description,
          typeIdList: this.searchParam.typeIdList,
          name: this.searchParam.name,
          page: this.page,
          limit: this.pageSize
        })
        this.tableData = data.list;
        this.totalPage = data.totalCount;
      },
      resetSearch() {
        this.searchParam = {
          code: '',
          description: '',
          typeIdList: [],
          name: '',
        }
      },
      addItem(idx, target, type) {
        let addnumber;
        if(type === 1) {
          addnumber = {
            typeId: ''
          }
        }else if(type === 2) {
          addnumber = {
            secondTypeId: '', 
            options:[], 
            detailFunctionList: [{switchNoId: '', functionId: ''}]
          }
        }else if(type === 3) {
          addnumber = {switchNoId: '', functionId: ''}
        }
        target.splice(idx+1, 0, addnumber)
      },

      removeItem(idx, target) {
        target.splice(idx,1)
      },
      async getDetailFunctionList(row) {
        row.options = await this.$httpN.postQ('pac/type/listByPid', {pid: row.secondTypeId});
        row.detailFunctionList = [{switchNoId: '', functionId: ''}]
      },
      async saveForm() {
        if(!formUtil.verifyData(this.form, this.formVerify)) return;
        let postForm = this.getPostForm();
        if(postForm.firstTypeList.length === 0) return formUtil.submitError('请选择一级分类');
        if(postForm.functionList.length === 0) return formUtil.submitError('请选择二级分类、功能');

        if(!await this.$httpN.postB('pac/product/saveBatch', postForm)) return;
        this.itemDialog = false;
        formUtil.submitSuccess('保存成功');
        this.searchItem(true);
      },
      getPostForm() {
        let postForm = {
          codeV1: this.form.codeV1,
          codeV2: this.form.codeV2,
          codeV3: this.form.codeV3,
          codeV4: this.form.codeV4,
          name: this.form.name,
          description: this.form.description,
          id: this.form.id,
          companyId: this.form.companyId,
          functionList: [],
          characterList: [],
          colorList: [],
          textureList: []
        }
        postForm.firstTypeList = this.form.firstTypeList.filter((item) => item.typeId);
        postForm.functionList = this.form.functionList.map((item) => {
          let detailArr = item.detailFunctionList.filter((detail) => detail.functionId);
          return {
            secondTypeId: item.secondTypeId,
            detailFunctionList: detailArr
          }
        })

        postForm.functionList = postForm.functionList.filter((item) => item.detailFunctionList.length > 0 && item.secondTypeId);

        if(!this.form.id) {
          postForm.characterList = this.characterList.map((item) => {
            if(item.name === '颜色' && item.val.length >0){
              item.val.forEach((color) => {
                item.options.forEach((option) => {
                  if(color === option.id){
                    postForm.colorList.push({
                      typeId: color,
                      typeName: option.name
                    })
                  }
                })
              })
            }
            if(item.name === '材质' && item.val.length >0){
              item.val.forEach((color) => {
                item.options.forEach((option) => {
                  if(color === option.id){
                    postForm.textureList.push({
                      typeId: color,
                      typeName: option.name
                    })
                  }
                })
              })
            }
            return {
              typeId: item.name === '颜色' || item.name === '材质' ? '':item.val
            }
          })
        }else {
          postForm.characterList = this.characterList.map((item) => {
            return {
              typeId: item.val
            }
          })
        }
        return postForm
      },
      async getCode() {
        if(!formUtil.verifyData(this.form, this.formVerify)) return;
        let postForm = this.getPostForm();
        if(postForm.firstTypeList.length === 0) return formUtil.submitError('请选择一级分类');
        if(postForm.functionList.length === 0) return formUtil.submitError('请选择二级分类、功能'); 
        let code = await this.$httpN.postB('pac/product/preview', postForm);
        formUtil.submitConfirm('您生成的产品编码为' + code + '是否保存到产品库', async ()=> {
          this.saveForm()
        })
      },
      async preview() {
         if(!formUtil.verifyData(this.form, this.formVerify)) return;
        let postForm = this.getPostForm();
        if(postForm.firstTypeList.length === 0) return formUtil.submitError('请选择一级分类');
        if(postForm.functionList.length === 0) return formUtil.submitError('请选择二级分类、功能'); 
        let code = await this.$httpN.postB('pac/product/preview', postForm);
        formUtil.submitConfirm('您生成的产品编码为' + code, async ()=> {

        })
      },
      openUpdate() {
        this.showUpdate = true;
        this.codeV4 = '';
      },
      async saveUpdate() {
        if(!await this.$httpN.postB('pac/product/updateV4', {
          id: this.form.id,
          codeV4: this.codeV4
        })) return;
        formUtil.submitSuccess('保存成功');
        this.showUpdate = false;
        this.itemDialog = false;
        this.searchItem(true);
      },
      //打开条目窗口
      async openItemDialog(item, isCheck) {
        this.itemDialog = true;
        this.isCheck = isCheck;
        if(item) {
          let detail = await this.$httpN.get('pac/product/info', {id: item.id});
          this.form = {
            codeV1: detail.codeV1,
            codeV2: detail.codeV2,
            codeV3: detail.codeV3,
            codeV4: detail.codeV4,
            name: detail.name,
            id: detail.id,
            companyId: detail.companyId,
            description: detail.description
          }
          this.characterList.forEach((item, idx) => {
            item.val = detail.characterList[idx].typeId;
          });
          this.form.firstTypeList = detail.firstTypeList.map((item) => {
            return {
              typeId: item.typeId
            }
          });
          this.form.functionList = [];
          detail.functionList.forEach(async (item) => {
            let obj = {
              secondTypeId: item.secondTypeId,
              detailFunctionList: item.detailFunctionList.map((child) => {
                return {
                  functionId: child.functionId,
                  switchNoId: child.switchNoId
                }
              })
            }
            obj.options = await this.$httpN.postQ('pac/type/listByPid', {pid: obj.secondTypeId});
            this.form.functionList.push(obj)
          })
        }else {
          formUtil.resetData(this.form);
          this.form.firstTypeList = [{typeId: ''}]
          this.form.functionList = [{secondTypeId: '', options:[], detailFunctionList: [{switchNoId: '', functionId: ''}]}]
          this.characterList.forEach((item) => {
            item.val = ''
          });
        }
      },
      sizeChangeHandle(limit) {
        this.pageSize = limit;
        this.searchItem(true);
      },
      currentChangeHandle(page) {
        this.page = page;
        this.searchItem();
      },
      delItem(item) {
        formUtil.submitConfirm('此操作将永久删除产品, 是否继续?', async ()=> {
          if(!await this.$httpN.postB('pac/product/delete', [item.id], false)) return;
          formUtil.submitSuccess('删除成功');
          this.searchItem(true)
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .form-wrapper{
    width: 70%;
    min-width: 1130px;
    margin: 0 auto;
    padding: 70px;
    padding-top: 10px;
    padding-left:0;
    position:relative;
  }
</style>
